//
//  YYTextLayout+Text.m
//  ZYOnlineSchool
//
//  Created by 毕武侠 on 2017/2/21.
//  Copyright © 2017年 bwx. All rights reserved.
//

#import "YYTextLayout+Text.h"
#import "TextImageViewAttachment.h"

@implementation YYTextLayout (Text)

+ (instancetype)layoutWithTexts:(NSArray <PaperTypeModel *>*)texts {
    return [self layoutWithSize:CGSizeMake(SCREEN_WIDTH - 24, HUGE) Texts:texts];
}

+ (instancetype)layoutWithSize:(CGSize)size
                         Texts:(NSArray <PaperTypeModel *>*)texts {
    
    NSMutableAttributedString *text = [self attributedStringWithText:texts];
    if (text.length == 0) return nil;
    
    YYTextContainer *container = [YYTextContainer containerWithSize:size];
    YYTextLayout *contentLayout = [YYTextLayout layoutWithContainer:container text:text];
    return contentLayout;
}

+ (NSMutableAttributedString *)attributedStringWithText:(NSArray *)contents {
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] init];
    text.font = [UIFont fontWithName:@"Heiti SC" size:16];
    text.color = [UIColor darkGrayColor];
    
    for (PaperTypeModel *model in contents) {
        if ([model.type isEqualToString:@"text"] && model.content) {
            //model.content = [model.content stringByReplacingOccurrencesOfString:@";" withString:@" "];
            NSMutableAttributedString *content = [[NSMutableAttributedString alloc] initWithString:model.content];
            content.font = [UIFont fontWithName:@"Heiti SC" size:16];
            if ([model.strong isEqualToString:@"strong"]) {
                content.font = [UIFont fontWithName:@"Arial-BoldMT" size:16];
            }
            if (model.color && [model.color isEqualToString:@"MainColor"]) {
                content.color = MainThemeColor;
            }
            [text appendAttributedString:content];
        } else if ([model.type isEqualToString:@"img"] && model.url) {
            NSString *imageURL = [NSString stringWithFormat:@"%@",model.url];
            //NSLog(@"imageURL:%@",imageURL);
            UIImageView *imageView = [[UIImageView alloc] init];
            [imageView setImageURL:[[NSURL alloc] initWithString:imageURL]];
            
            NSAttributedString *img = [self attachmentStringWithContentMode:UIViewContentModeScaleToFill
                                                           attacmentContent:imageView
                                                             attachmentSize:model.imageSize
                                                              attachmentURL:imageURL
                                                                alignToFont:[UIFont systemFontOfSize:16]
                                                                  alignment:YYTextVerticalAlignmentBottom];
            [text appendAttributedString:img];
        } else if ([model.type isEqualToString:@"br"]) {
            NSMutableAttributedString *content = [[NSMutableAttributedString alloc] initWithString:@"\n"];
            content.font = [UIFont fontWithName:@"Heiti SC" size:16];
            [text appendAttributedString:content];
        }
    }
    return text;
}

+ (NSAttributedString *)attachmentWithFontSize:(CGSize)fontSize imageURL:(NSString *)imageURL shrink:(BOOL)shrink {
    /*
     URL 嵌入的图片，比临近的字体要小一圈。。
     这里模拟一下 Heiti SC 字体，然后把图片缩小一下。
     */
    CGFloat ascent  = fontSize.height;
    CGFloat descent = fontSize.height;
    CGRect bounding = CGRectMake(0, 0, fontSize.width, fontSize.height);
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(ascent - (bounding.size.height + bounding.origin.y), 0, descent + bounding.origin.y, 0);
    CGSize size = fontSize;
    
    if (shrink) {
        // 缩小~
        CGFloat scale = 1 / 10.0;
        contentInsets.top += fontSize.height * scale;
        contentInsets.bottom += fontSize.height * scale;
        contentInsets.left += fontSize.width * scale;
        contentInsets.right += fontSize.width * scale;
        contentInsets = UIEdgeInsetPixelFloor(contentInsets);
        size = CGSizeMake(fontSize.width - fontSize.width * scale * 2, fontSize.height - fontSize.height * scale * 2);
        size = CGSizePixelRound(size);
    }
    
    YYTextRunDelegate *delegate = [YYTextRunDelegate new];
    delegate.ascent = ascent;
    delegate.descent = descent;
    delegate.width = bounding.size.width;
    
    TextImageViewAttachment *attachment = [TextImageViewAttachment new];
    attachment.contentMode = UIViewContentModeScaleAspectFit;
    //    attachment.contentInsets = contentInsets;
    attachment.size = size;
    attachment.imageURL = [[NSURL alloc] initWithString:imageURL];
    
    NSMutableAttributedString *attachText = [self attachmentStringWithContentMode:UIViewContentModeScaleAspectFit
                                                                 attacmentContent:attachment
                                                                   attachmentSize:size
                                                                    attachmentURL:imageURL
                                                                      alignToFont:[UIFont systemFontOfSize:16]
                                                                        alignment:YYTextVerticalAlignmentBottom];
    
    //    NSMutableAttributedString *atr = [[NSMutableAttributedString alloc] initWithString:YYTextAttachmentToken];
    //    [atr setTextAttachment:attachment range:NSMakeRange(0, atr.length)];
    //    atr.lineHeightMultiple = size.height;
    //    CTRunDelegateRef ctDelegate = delegate.CTRunDelegate;
    //    [attachText setRunDelegate:ctDelegate range:NSMakeRange(0, attachText.length)];
    //    if (ctDelegate) CFRelease(ctDelegate);
    
    return attachText;
}

+ (NSMutableAttributedString *)attachmentStringWithContentMode:(UIViewContentMode)contentMode
                                              attacmentContent:(id)content
                                                attachmentSize:(CGSize)attachmentSize
                                                 attachmentURL:(NSString *)imageURL
                                                   alignToFont:(UIFont *)font
                                                     alignment:(YYTextVerticalAlignment)alignment {
    NSMutableAttributedString *atr = [[NSMutableAttributedString alloc] initWithString:YYTextAttachmentToken];
    
    TextImageViewAttachment *attach = [TextImageViewAttachment new];
    attach.contentMode = contentMode;
    attach.size = attachmentSize;
    attach.imageURL = [[NSURL alloc] initWithString:imageURL];
    attach.content = content;
    [atr setTextAttachment:attach range:NSMakeRange(0, atr.length)];
    
    YYTextRunDelegate *delegate = [YYTextRunDelegate new];
    delegate.width = attachmentSize.width;
    switch (alignment) {
        case YYTextVerticalAlignmentTop: {
            delegate.ascent = font.ascender;
            delegate.descent = attachmentSize.height - font.ascender;
            if (delegate.descent < 0) {
                delegate.descent = 0;
                delegate.ascent = attachmentSize.height;
            }
        } break;
        case YYTextVerticalAlignmentCenter: {
            CGFloat fontHeight = font.ascender - font.descender;
            CGFloat yOffset = font.ascender - fontHeight * 0.5;
            delegate.ascent = attachmentSize.height * 0.5 + yOffset;
            delegate.descent = attachmentSize.height - delegate.ascent;
            if (delegate.descent < 0) {
                delegate.descent = 0;
                delegate.ascent = attachmentSize.height;
            }
        } break;
        case YYTextVerticalAlignmentBottom: {
            delegate.ascent = attachmentSize.height + font.descender;
            delegate.descent = -font.descender;
            if (delegate.ascent < 0) {
                delegate.ascent = 0;
                delegate.descent = attachmentSize.height;
            }
        } break;
        default: {
            delegate.ascent = attachmentSize.height;
            delegate.descent = 0;
        } break;
    }
    
    CTRunDelegateRef delegateRef = delegate.CTRunDelegate;
    [atr setRunDelegate:delegateRef range:NSMakeRange(0, atr.length)];
    if (delegate) CFRelease(delegateRef);
    
    return atr;
}

@end
